package org.example.yuewen.solution5;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: lynn
 * @Descript: map转对象，核心是 Object o=beanClass.newInstance
 * f= beanClass.getDeclaredFields() 取到对象属性
 *  f.set(o,map.get(beanClass.getDeclaredFields().getName))
 *
 * @date: 2021/3/28 16:35
 * @version: 1.0
 */
public class MapToObject {

    public static void main(String[] args) {
        Map<String,Object> map=new HashMap<>();
        map.put("name","lynn");
        map.put("age","18");
        Student student = (Student)map2object(map, Student.class);
        System.out.println(student);
    }

    public  static Object map2object(Map<String,Object> map,Class<?> beanClass){
        if (map==null){
            return null;
        }
        Object object = null;
        try {
            object=beanClass.newInstance();
        //子类属性：  beanClass.getDeclaredFields()
            for (Field f:beanClass.getDeclaredFields()){
                //将指定对象变量上此 Field 对象表示的字段设置为指定的新值.
                int mod = f.getModifiers();
                //判断不能是静态和Final属性
                if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){
                    continue;
                }
                f.setAccessible(true);
                //要反射的对象，后面是域
                f.set(object,map.get(f.getName()));
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }
}
